package com.framework.controller.system;

import java.io.IOException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.framework.annotation.SystemLog;
import com.framework.axis2.Axis2Client;
import com.framework.controller.index.BaseController;
import com.framework.entity.DatacenterFormMap;
import com.framework.entity.DatasourceFormMap;
import com.framework.entity.LogSMSFormMap;
import com.framework.entity.ProductTreeFormMap;
import com.framework.entity.base.FormMap;
import com.framework.entity.factory.FormmapFactory;
import com.framework.entity.AccessoryFormMap;
import com.framework.entity.ClientDatasourceFormMap;
import com.framework.entity.view.DatasourceFuncViewFormMap;
import com.framework.entity.view.UsersourceViewFormMap;
import com.framework.plugin.PageView;
import com.framework.util.Common;
import com.framework.util.HttpConnectionPostUtils;
import com.framework.util.PasswordHelper;
import com.framework.util.datasource.InvokeBatUtil;

/**
 * 本质：控制型逻辑，拥有强大的权利与义务 信息的拦截与处理
 * 
 * @author 李品良:
 * @version 创建时间：2016年8月15日 下午3:12:27 类说明
 */
@Controller
@RequestMapping("/interface/")
public class InterfaceController extends BaseController {

	/**
	 * ---------------- 备注方式 ，下面其他方法不再赘述 ------------------ 判断手机号码是否是唯一的 （方法作用）
	 * 参数cellphone （参数） 对象型关系逻辑 （逻辑方式）
	 * 
	 * @author 李品良
	 * @return success（不存在） exist（存在） failed（失败）
	 * @throws Exception
	 */
	@ResponseBody
	// 此处为记录AOP拦截Controller记录用户操作
	@RequestMapping("checkPhoneNum")
	public String checkPhoneNum() throws Exception {
		String phoneNumber = getPara("cellphone");
		if (Common.isCellphone(phoneNumber)) {
			DatacenterFormMap datacenterFormMap = new DatacenterFormMap();
			datacenterFormMap.put("cellphone", phoneNumber);
			datacenterFormMap = datacenterFormMap.findbyFrist();
			if (datacenterFormMap == null) {
				return "success";
			} else {
				return "exist";
			}
		}
		return "failed";
	}

	
	
	@RequestMapping("getSpecialResult")
	@SystemLog(module = "interface", methods = "BaseController-getSpecialResult") // 凡需要处理业务逻辑的.都需要记录操作日志
	@ResponseBody
	public Object getSpecialResult() throws Exception {
		Object result=super.getSpecialResult();
		return result;
	}

	
	@ResponseBody
	@RequestMapping("getPageResult")
	public PageView getPageResult(String draw, String length, String start) throws Exception {
		pageView =super.getPageResult(draw, length, start);
		return pageView;
	}
	/*
	 * @ResponseBody
	 * 
	 * @RequestMapping("findDBTables") public void findDBTables() throws
	 * Exception { DatasourceFormMap datasourceFormMap=new DatasourceFormMap();
	 * datasourceFormMap=datasourceFormMap.mapper().findDBTables("heke-con");
	 * System.out.println(datasourceFormMap); }
	 */
	/**
	 * 得到企业的CRM套餐的详细信息 参数 db_name
	 * 
	 * @author 李品良 创建时间：2016年9月28日 下午3:05:54
	 * @return DatasourceFuncViewFormMap null
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("enTimeInfo")
	public DatasourceFuncViewFormMap enTimeInfo() throws Exception {
		DatasourceFuncViewFormMap datasourceFuncViewFormMap = getMapformDataMap(DatasourceFuncViewFormMap.class,
				getMapFromRequest());
		if (datasourceFuncViewFormMap.containsKey("db_name")) {
			datasourceFuncViewFormMap.put("name", "CRM");
			return datasourceFuncViewFormMap.findbyFrist();
		}
		return null;
	}

	/**
	 * 得到企业的人数套餐的详细信息 参数 db_name
	 * 
	 * @author 李品良 创建时间：2016年9月28日 下午3:05:54
	 * @return DatasourceFuncViewFormMap null
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("enEntityInfo")
	public DatasourceFuncViewFormMap enEntityInfo() throws Exception {
		DatasourceFuncViewFormMap datasourceFuncViewFormMap = getMapformDataMap(DatasourceFuncViewFormMap.class,
				getMapFromRequest());
		if (datasourceFuncViewFormMap.containsKey("db_name")) {
			datasourceFuncViewFormMap.put("name", "人数套餐");
			return datasourceFuncViewFormMap.findbyFrist();
		}
		return null;
	}

	/**
	 * 得到企业套餐的状态，是否过期 参数 db_name
	 * 
	 * @author 李品良 创建时间：2016年9月28日 下午3:05:54
	 * @return true false
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("enStatus")
	public boolean enStatus() throws Exception {
		DatasourceFuncViewFormMap datasourceFuncViewFormMap = enTimeInfo();
		if (datasourceFuncViewFormMap == null) {
			return false;
		} else {
			if (datasourceFuncViewFormMap.getStr("spec_value").contains("免费")) {
				return true;
			}
			String expire_time = datasourceFuncViewFormMap.get("expire_time").toString();
			int index = Common.compareDate(expire_time);
			if (index == -1) {
				return true;
			} else {
				String id = datasourceFuncViewFormMap.getStr("id");
				datasourceFuncViewFormMap.clear();
				datasourceFuncViewFormMap.put("id", id);
				datasourceFuncViewFormMap.put("func_status", 1);
				datasourceFuncViewFormMap.update();
				return false;
			}
		}
	}

	public ProductTreeFormMap findFrom() throws Exception {
		ProductTreeController productTreeController = new ProductTreeController();
		return productTreeController.findForm();

	}

	/**
	 * 客户数据库初始化 发送初始化用户表信息
	 * 
	 * @author 李品良 创建时间：2016年9月14日 下午4:20:54
	 * @return
	 * @throws Exception
	 */
	// @ResponseBody
	// @RequestMapping("initDBUser")
	public List<UsersourceViewFormMap> initDBUser() throws Exception {
		HashMap<String, Object> hashMap = getMapFromRequest();
		String db_name = hashMap.get("db_name").toString();
		UsersourceViewFormMap formap = getMapformDataMap(UsersourceViewFormMap.class, hashMap);
		List<UsersourceViewFormMap> list = formap.findByNames();
		return list;
	}

	/**
	 * 客户数据库初始化 发送初始化公司信息表
	 * 
	 * @author 李品良 创建时间：2016年9月14日 下午4:20:54
	 * @return
	 * @throws Exception
	 */
	// @ResponseBody
	// @RequestMapping("initDBCompanyInfo")
	public List<DatasourceFormMap> initDBCompanyInfo() throws Exception {
		HashMap<String, Object> hashMap = getMapFromRequest();
		DatasourceFormMap formMap = getMapformDataMap(DatasourceFormMap.class, hashMap);
		List<DatasourceFormMap> list = formMap.findByNames();
		return list;
	}

	/**
	 * 登录接口 参数手机
	 * 
	 * @author 李品良
	 * @param request
	 * @return List<UsersourceViewFormMap>
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("getDBInfoViaCellphone")
	public List<UsersourceViewFormMap> getDBInfoViaCellphone(HttpServletRequest request) throws Exception {
		String cellphone = request.getParameter("cellphone");
		if (!Common.isCellphone(cellphone)) {
			return null;
		} else {
			UsersourceViewFormMap usersourceViewFormMap = getMapformDataMap(UsersourceViewFormMap.class,
					getMapFromRequest());
			if (cellphone.contains("admin") || cellphone.contains("ROOT")) {
				usersourceViewFormMap.put("username", cellphone);
			} else if (Common.isNumeric(cellphone)) {
				usersourceViewFormMap.put("cellphone", cellphone);
			} else {
				return null;
			}
			usersourceViewFormMap.put("dc_status", 1);// 用户状态
			usersourceViewFormMap.put("c_d_status", 1); // 用户企业关系状态--伪删除

			List<UsersourceViewFormMap> list = usersourceViewFormMap.findByNames();
			return list;
		}
	}

	public static void main(String[] args) throws IOException {
		String url = "http://localhost:8080/hewke-con/interface/registeEnUser.shtml";
		HashMap<String, Object> hashMap = new HashMap<>();
		hashMap.put("username", "李四");
		hashMap.put("cellphone", "13265071310");
		hashMap.put("password", "5601564a");
		StringBuffer sb = HttpConnectionPostUtils.readContentFromPost(url, hashMap);
		System.out.println(sb.toString());
	}

	/**
	 * 传入，电话，和密码，根据电话检索得到id，接着加密密码，然后覆盖 参数 cellphone password
	 * 
	 * @author 李品良 创建时间：2016年8月25日 下午2:13:29
	 * @return success failed
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("updateEnUserPassword")
	public String updateEnUserPassword() {
		try {
			HashMap<String, Object> hashMap = getMapFromRequest();
			DatacenterFormMap datacenterFormMap = getMapformDataMap(DatacenterFormMap.class, hashMap);
			if (datacenterFormMap.containsKey("cellphone") && datacenterFormMap.size() == 2) {
				String password = datacenterFormMap.getStr("password");
				datacenterFormMap.remove("password");
				datacenterFormMap = datacenterFormMap.findbyFrist();
				///
				if (datacenterFormMap != null) {
					PasswordHelper passwordHelper = new PasswordHelper();
					String salt = passwordHelper.getSalt();
					String newPassword = passwordHelper.encryptPassword(datacenterFormMap.getStr("cellphone"), password,
							salt);
					datacenterFormMap.put("credentialsSalt", salt);
					datacenterFormMap.put("password", newPassword);

					datacenterFormMap.update();

					return "success";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "failed";
		}
		return "failed";

	}

	/**
	 * 更新企业名字 传入，db_name,enterprise
	 * 
	 * @author 李品良 创建时间：2016年8月25日 下午2:13:29
	 * @return
	 * @throws Exception
	 */
	// @ResponseBody
	// @RequestMapping("updateEnName")
	public String updateEnName() {
		try {
			HashMap<String, Object> hashMap = getMapFromRequest();
			DatasourceFormMap datasourceFormMap = getMapformDataMap(DatasourceFormMap.class, hashMap);
			if (datasourceFormMap.containsKey("db_name") && datasourceFormMap.size() == 2) {
				String enterprise = datasourceFormMap.getStr("enterprise");
				datasourceFormMap.remove("enterprise");
				datasourceFormMap = datasourceFormMap.findbyFrist();
				///
				if (datasourceFormMap != null) {
					datasourceFormMap.put("enterprise", enterprise);
					datasourceFormMap.update();
					return "success";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "failed";
		}
		return "failed";

	}

	/**
	 * 1.判断是否已经存在 传入，电话，和密码，根据电话检索得到id，接着加密密码，然后覆盖 2.先判断db_name是否存在该数据库
	 * ，再判断企业状态，再判断企业套餐情况 参数 cellphone db_name password
	 * 
	 * @author 李品良 创建时间：2016年8月25日 下午2:13:29
	 * @return 'db is not exist' 'enterprise is not active' 'Func is Overflow'
	 *         'failed' 'success' 'people is exist'
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("registeEnUser")
	public String registeEnUser() {
		try {
			HashMap<String, Object> hashMap = getMapFromRequest();
			DatacenterFormMap datacenterFormMap = getMapformDataMap(DatacenterFormMap.class, hashMap);
			UsersourceViewFormMap usersourceViewFormMap = new UsersourceViewFormMap();
			usersourceViewFormMap.put("cellphone", datacenterFormMap.get("cellphone"));
			usersourceViewFormMap.put("status", 1);// 注册失败的情况是0，那么就没有必要登录了
			usersourceViewFormMap = usersourceViewFormMap.findbyFrist();

			boolean flag = false;
			if (datacenterFormMap.get("db_name") != null) {
				DatasourceFormMap datasourceFormMap = getFormMap(DatasourceFormMap.class);
				List<DatasourceFormMap> list = datasourceFormMap.findByAttribute("db_name",
						datacenterFormMap.get("db_name"));
				if (list.size() == 0) {
					return "db is not exist";
				}
				String status = list.get(0).get("status").toString();
				if (status.equals("0")) {
					return "enterprise is not active";
				}
				flag = isFuncOverFlow(datacenterFormMap.getStr("db_name"));
			}

			if (flag) {
				return "Func is Overflow";
			}

			if (usersourceViewFormMap != null) {
				return registeEnUserExist(datacenterFormMap);
			}

			if (datacenterFormMap.containsKey("cellphone") && datacenterFormMap.size() > 2) {
				String password = datacenterFormMap.getStr("password");
				String db_name = datacenterFormMap.getStr("db_name");
				if (db_name.equals("dataSource")) {
					return "failed";
				}
				datacenterFormMap.remove("password");
				///
				if (datacenterFormMap.findbyFrist() == null) {
					PasswordHelper passwordHelper = new PasswordHelper();
					String salt = passwordHelper.getSalt();
					String newPassword = passwordHelper.encryptPassword(datacenterFormMap.getStr("cellphone"), password,
							salt);
					datacenterFormMap.put("credentialsSalt", salt);
					datacenterFormMap.put("password", newPassword);
					datacenterFormMap.put("username", datacenterFormMap.getStr("cellphone"));

					// 找到父级数据库
					DatasourceFormMap datasourceFormMap = FormmapFactory.getBeanFormMap(DatasourceFormMap.class);
					datasourceFormMap.put("db_name", db_name);
					datasourceFormMap = datasourceFormMap.findbyFrist();

					if (datasourceFormMap == null) {
						logger = getLogger(InterfaceController.class);
						logger.error("failed   datasourceFormMap is null");
						return "failed";
					}
					datacenterFormMap = datacenterFormMap.replace();
					// 保存关系
					ClientDatasourceFormMap clientDatasourceFormMap = FormmapFactory
							.getBeanFormMap(ClientDatasourceFormMap.class);
					clientDatasourceFormMap.put("client_id", datacenterFormMap.get("id"));
					clientDatasourceFormMap.put("datasource_id", datasourceFormMap.get("id"));
					clientDatasourceFormMap.put("status", 1);
					clientDatasourceFormMap.save();
					Integer amount = datasourceFormMap.getInt("enterprise_entity");
					datasourceFormMap.put("enterprise_entity", ++amount);
					datasourceFormMap.update();
					updateEnUserState(db_name, amount);

					datacenterFormMap.put("status", 1);
					return "success";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "failed";
		}
		return "failed";
	}

	/**
	 * 添加冻结企业用户 1.判断是否已经存在 传入，电话，和密码，根据电话检索得到id，接着加密密码，然后覆盖 关系型逻辑处理 参数cellphone
	 * db_name
	 * 
	 * @author 李品良 创建时间：2016年8月25日 下午2:13:29
	 * @return "Finding is over" "Finding is zero or already delete"
	 *         "logDeleteEnUser failed" "success" "failed"
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("addFreezeEnUser")
	public String addFreezeEnUser() throws Exception {
		HashMap<String, Object> hashMap = getMapFromRequest();
		DatacenterFormMap datacenterFormMap = getMapformDataMap(DatacenterFormMap.class, hashMap);
		if (datacenterFormMap.get("db_name") != null) {
			DatasourceFormMap datasourceFormMap = getFormMap(DatasourceFormMap.class);
			List<DatasourceFormMap> list = datasourceFormMap.findByAttribute("db_name",
					datacenterFormMap.get("db_name"));
			if (list.size() == 0) {
				return "db is not exist";
			}
			String status = list.get(0).get("status").toString();
			if (status.equals("0")) {
				return "enterprise is not active";
			}
		}
		if (datacenterFormMap.containsKey("cellphone")) {
			String password = datacenterFormMap.get("password") == null ? "12345678"
					: datacenterFormMap.getStr("password");
			String db_name = datacenterFormMap.getStr("db_name");
			if (db_name.equals("dataSource")) {
				return "failed";
			}
			datacenterFormMap.remove("password");
			///
			if (datacenterFormMap.findbyFrist() == null) {
				PasswordHelper passwordHelper = new PasswordHelper();
				String salt = passwordHelper.getSalt();
				String newPassword = passwordHelper.encryptPassword(datacenterFormMap.getStr("cellphone"), password,
						salt);
				datacenterFormMap.put("credentialsSalt", salt);
				datacenterFormMap.put("password", newPassword);
				datacenterFormMap.put("username", datacenterFormMap.getStr("cellphone"));

				// 找到父级数据库
				DatasourceFormMap datasourceFormMap = FormmapFactory.getBeanFormMap(DatasourceFormMap.class);
				datasourceFormMap.put("db_name", db_name);
				datasourceFormMap = datasourceFormMap.findbyFrist();

				if (datasourceFormMap == null) {
					logger = getLogger(InterfaceController.class);
					logger.error("failed   datasourceFormMap is null");
					return "failed";
				}
				datacenterFormMap = datacenterFormMap.replace();
				// 保存关系
				ClientDatasourceFormMap clientDatasourceFormMap = FormmapFactory
						.getBeanFormMap(ClientDatasourceFormMap.class);
				clientDatasourceFormMap.put("client_id", datacenterFormMap.get("id"));
				clientDatasourceFormMap.put("datasource_id", datasourceFormMap.get("id"));
				clientDatasourceFormMap.put("status", 2);
				clientDatasourceFormMap.save();
				return "success";
			} else {
				// 用户存在，而不存在于任何公司\
				UsersourceViewFormMap usersourceViewFormMap = FormmapFactory
						.getBeanFormMap(UsersourceViewFormMap.class);
				usersourceViewFormMap.put("cellphone", datacenterFormMap.get("cellphone"));
				usersourceViewFormMap.put("db_name", db_name);
				usersourceViewFormMap = usersourceViewFormMap.findbyFrist();
				// 公司存在，而用户不存在于该公司
				if (usersourceViewFormMap == null) {
					return registeFreezeEnUserExist(datacenterFormMap);
				} else {
					return "user is exist in this enterprise";
				}
			}
		}
		return "failed";
	}

	/**
	 * 冻结企业用户 1.判断是否已经存在 传入，电话，和密码，根据电话检索得到id，接着加密密码，然后覆盖 关系型逻辑处理 参数cellphone
	 * db_name
	 * 
	 * @author 李品良 创建时间：2016年8月25日 下午2:13:29
	 * @return "Finding is over" "Finding is zero or already delete"
	 *         "logDeleteEnUser failed" "success" "failed"
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("freezeEnUser")
	public String freezeEnUser() throws InstantiationException, IllegalAccessException {
		UsersourceViewFormMap usersourceViewFormMap = getMapformDataMap(UsersourceViewFormMap.class,
				getMapFromRequest());
		if (usersourceViewFormMap.containsKey("cellphone") && usersourceViewFormMap.containsKey("db_name")
				&& usersourceViewFormMap.size() == 2) {
			List<UsersourceViewFormMap> list = usersourceViewFormMap.findByNames();
			if (list.size() > 1) {
				return "overflow";
			} else if (list.size() == 0) {
				return "zero";
			} else {
				Object id = list.get(0).get("c_d_id");
				Object ds_id = list.get(0).get("ds_id");
				String c_d_status = list.get(0).getStr("c_d_status");
				if (!"1".equals(c_d_status)) {
					return "illegal status";
				}
				ClientDatasourceFormMap clientDatasourceFormMap = FormmapFactory
						.getBeanFormMap(ClientDatasourceFormMap.class);
				clientDatasourceFormMap.clear();
				clientDatasourceFormMap.put("id", id);
				clientDatasourceFormMap.put("status", 2);
				try {
					// 修改套餐，企业人数
					DatasourceFormMap datasourceFormMap = FormmapFactory.getBeanFormMap(DatasourceFormMap.class);
					datasourceFormMap.clear();
					datasourceFormMap.put("id", ds_id);
					datasourceFormMap = datasourceFormMap.findbyFrist();
					Integer entity = datasourceFormMap.getInt("enterprise_entity");
					entity--;
					datasourceFormMap.put("enterprise_entity", entity);
					clientDatasourceFormMap.update();
					datasourceFormMap.update();

					updateEnUserState(usersourceViewFormMap.getStr("db_name"), entity);

				} catch (Exception e) {
					e.printStackTrace();
					return "freezeEnUser failed";
				}
				return "success";
			}
		}
		return "failed";
	}

	/**
	 * 解冻用户 1.判断是否已经存在 传入，电话，和密码，根据电话检索得到id，接着加密密码，然后覆盖 参数cellphone db_name
	 * 
	 * @author 李品良 创建时间：2016年8月25日 下午2:13:29
	 * @return "Finding is over" "Finding is zero or already delete"
	 *         "logDeleteEnUser failed" "success" "failed"
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("unfreezeEnUser")
	public String unfreezeEnUser() throws Exception {
		UsersourceViewFormMap usersourceViewFormMap = getMapformDataMap(UsersourceViewFormMap.class,
				getMapFromRequest());
		if (usersourceViewFormMap.containsKey("cellphone") && usersourceViewFormMap.containsKey("db_name")
				&& usersourceViewFormMap.size() == 2) {
			usersourceViewFormMap = usersourceViewFormMap.findbyFrist();
			if (usersourceViewFormMap != null) {
				String c_d_status = usersourceViewFormMap.getStr("c_d_status");
				if (!c_d_status.equals("2")) {
					return "enUser hasn't already freezed";
				} else {
					String db_name = usersourceViewFormMap.getStr("db_name");
					String ds_id = usersourceViewFormMap.getStr("ds_id");
					String c_d_id = usersourceViewFormMap.getStr("c_d_id");
					Integer entity = usersourceViewFormMap.getInt("enterprise_entity");
					entity++;

					if (isFuncOverFlow(db_name)) {
						return "Func is overtop";
					}
					ClientDatasourceFormMap operation_formmap = FormmapFactory
							.getBeanFormMap(ClientDatasourceFormMap.class);
					operation_formmap.put("id", c_d_id);
					operation_formmap.put("status", 1);

					DatasourceFormMap operation_formmap2 = FormmapFactory.getBeanFormMap(DatasourceFormMap.class);
					operation_formmap2.put("id", ds_id);
					operation_formmap2.put("enterprise_entity", entity);

					operation_formmap.update();
					operation_formmap2.update();
					return "success";
				}
			}
		}
		return "failed";
	}

	/**
	 * 1.判断是否已经存在 传入，电话，和密码，根据电话检索得到id，接着加密密码，然后覆盖 参数cellphone db_name
	 * 
	 * @author 李品良 创建时间：2016年8月25日 下午2:13:29
	 * @return "Finding is over" "Finding is zero or already delete"
	 *         "logDeleteEnUser failed" "success" "failed"
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("logicDeleteEnUser")
	public String logicDeleteEnUser() throws InstantiationException, IllegalAccessException {
		UsersourceViewFormMap usersourceViewFormMap = getMapformDataMap(UsersourceViewFormMap.class,
				getMapFromRequest());
		if (usersourceViewFormMap.containsKey("cellphone") && usersourceViewFormMap.containsKey("db_name")
				&& usersourceViewFormMap.size() == 2) {
			List<UsersourceViewFormMap> list = usersourceViewFormMap.findByNames();
			if (list.size() > 1) {
				return "overflow";
			} else if (list.size() == 0) {
				return "zero";
			} else {
				Object id = list.get(0).get("c_d_id");
				Object ds_id = list.get(0).get("ds_id");
				String c_d_status = list.get(0).getStr("c_d_status");
				if (!"1".equals(c_d_status)) {
					return "illegal status";
				}
				ClientDatasourceFormMap clientDatasourceFormMap = FormmapFactory
						.getBeanFormMap(ClientDatasourceFormMap.class);
				clientDatasourceFormMap.clear();
				clientDatasourceFormMap.put("id", id);
				clientDatasourceFormMap.put("status", 3);
				try {
					// 修改套餐，企业人数
					DatasourceFormMap datasourceFormMap = FormmapFactory.getBeanFormMap(DatasourceFormMap.class);
					datasourceFormMap.clear();
					datasourceFormMap.put("id", ds_id);
					datasourceFormMap = datasourceFormMap.findbyFrist();
					Integer entity = datasourceFormMap.getInt("enterprise_entity");
					entity--;
					datasourceFormMap.put("enterprise_entity", entity);
					clientDatasourceFormMap.update();
					datasourceFormMap.update();

					updateEnUserState(usersourceViewFormMap.getStr("db_name"), entity);

				} catch (Exception e) {
					e.printStackTrace();
					return "logDeleteEnUser failed";
				}
				return "success";
			}
		}
		return "failed";
	}

	/**
	 * 1.判断是否已经存在 传入，电话，和密码，根据电话检索得到id，接着加密密码，然后覆盖 参数cellphone db_name
	 * 
	 * @author 李品良 创建时间：2016年8月25日 下午2:13:29
	 * @return "Finding is over" "Finding is zero or already delete"
	 *         "logDeleteEnUser failed" "success" "failed"
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("logicReliveEnUser")
	public String logicReliveEnUser() throws InstantiationException, IllegalAccessException {
		UsersourceViewFormMap usersourceViewFormMap = getMapformDataMap(UsersourceViewFormMap.class,
				getMapFromRequest());
		if (usersourceViewFormMap.containsKey("cellphone") && usersourceViewFormMap.containsKey("db_name")
				&& usersourceViewFormMap.size() == 2) {
			List<UsersourceViewFormMap> list = usersourceViewFormMap.findByNames();
			if (list.size() > 1) {
				return "Finding is over";
			} else if (list.size() == 0) {
				return "Finding is zero";
			} else {
				Object id = list.get(0).get("c_d_id");
				Object ds_id = list.get(0).get("ds_id");
				ClientDatasourceFormMap clientDatasourceFormMap = FormmapFactory
						.getBeanFormMap(ClientDatasourceFormMap.class);
				clientDatasourceFormMap.clear();
				clientDatasourceFormMap.put("id", id);
				clientDatasourceFormMap.put("status", 1);
				try {
					// 修改套餐，企业人数
					DatasourceFormMap datasourceFormMap = FormmapFactory.getBeanFormMap(DatasourceFormMap.class);
					datasourceFormMap.clear();
					datasourceFormMap.put("id", ds_id);
					datasourceFormMap = datasourceFormMap.findbyFrist();
					Integer entity = datasourceFormMap.getInt("enterprise_entity");
					entity--;
					datasourceFormMap.put("enterprise_entity", entity);
					clientDatasourceFormMap.update();
					datasourceFormMap.update();

					updateEnUserState(usersourceViewFormMap.getStr("db_name"), entity);

				} catch (Exception e) {
					e.printStackTrace();
					return "logDeleteEnUser failed";
				}
				return "success";
			}
		}
		return "failed";
	}

	/**
	 * 修改人数套餐状态
	 * 
	 * @author 李品良 创建时间：2016年10月13日 下午7:39:47
	 * @param db_name
	 * @param amount
	 *            当前套餐人数
	 * @return "system failed" "datasourceFuncViewFormMap is null"
	 *         "state is changed" "success"
	 * @throws Exception
	 */
	@SuppressWarnings("unused")
	private String updateEnUserState(String db_name, Integer amount) throws Exception {
		Integer func_status = null;
		DatasourceFuncViewFormMap datasourceFuncViewFormMap = new DatasourceFuncViewFormMap();
		datasourceFuncViewFormMap.put("db_name", db_name);
		datasourceFuncViewFormMap.put("name", "人数套餐");
		datasourceFuncViewFormMap = datasourceFuncViewFormMap.findbyFrist();
		func_status = datasourceFuncViewFormMap.getInt("func_status");

		if (Common.isEmpty(datasourceFuncViewFormMap.getStr("spec_value"))) {
			return "system failed";
		}
		Integer top = datasourceFuncViewFormMap.getInt("spec_value");
		Integer id = datasourceFuncViewFormMap.getInt("id");

		if (datasourceFuncViewFormMap == null) {
			return "datasourceFuncViewFormMap is null";
		}

		datasourceFuncViewFormMap.clear();

		if (amount >= top) {
			datasourceFuncViewFormMap.put("func_status", 1);
			datasourceFuncViewFormMap.put("id", id);
			datasourceFuncViewFormMap.update();
			return "state is changed";
		} else {
			if (func_status == 1) {
				datasourceFuncViewFormMap.put("func_status", 0);
				datasourceFuncViewFormMap.put("id", id);
				datasourceFuncViewFormMap.update();
			}
		}

		return "success";
	}

	/**
	 * 
	 * @author Lyon 创建时间：2016年11月15日 下午2:37:08
	 * @param db_name
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	private boolean isFuncOverFlow(String db_name) throws InstantiationException, IllegalAccessException {
		DatasourceFuncViewFormMap datasourceFuncViewFormMap = FormmapFactory
				.getBeanFormMap(DatasourceFuncViewFormMap.class);
		datasourceFuncViewFormMap.put("db_name", db_name);
		datasourceFuncViewFormMap.put("name", "人数套餐");
		datasourceFuncViewFormMap.put("status", "1");
		datasourceFuncViewFormMap = datasourceFuncViewFormMap.findbyFrist();
		if (datasourceFuncViewFormMap != null) {
			Integer entity = datasourceFuncViewFormMap.getInt("enterprise_entity");// 实际人数
			Integer spec_value = datasourceFuncViewFormMap.getInt("spec_value");// 套餐值
			if (spec_value > entity) {
				return false;
			} else {
				return true;
			}
		}
		return false;
	}

	/**
	 * 当企业用户存在时，添加 企业用户关系
	 * 
	 * @author Lyon 创建时间：2016年11月5日 上午9:40:21
	 * @param datacenterFormMap
	 * @return "failed" "success" "people is exist"
	 * @throws Exception
	 */
	public String registeEnUserExist(DatacenterFormMap datacenterFormMap) throws Exception {
		if (datacenterFormMap.containsKey("cellphone") && datacenterFormMap.size() > 2) {
			String db_name = datacenterFormMap.getStr("db_name");
			List<DatacenterFormMap> list = datacenterFormMap.findByAttribute("cellphone",
					datacenterFormMap.get("cellphone"));
			datacenterFormMap = list.get(0);
			// 找到父级数据库
			DatasourceFormMap datasourceFormMap = new DatasourceFormMap();
			datasourceFormMap.put("db_name", db_name);
			datasourceFormMap = datasourceFormMap.findbyFrist();

			if (datasourceFormMap == null) {
				return "failed";
			}
			// 保存关系
			ClientDatasourceFormMap clientDatasourceFormMap = new ClientDatasourceFormMap();
			clientDatasourceFormMap.put("client_id", datacenterFormMap.get("id"));
			clientDatasourceFormMap.put("datasource_id", datasourceFormMap.get("id"));
			clientDatasourceFormMap.put("status", 1);
			if (clientDatasourceFormMap.findbyFrist() == null) {
				clientDatasourceFormMap.save();
				Integer amount = datasourceFormMap.getInt("enterprise_entity");
				datasourceFormMap.put("enterprise_entity", ++amount);
				datasourceFormMap.update();
				updateEnUserState(db_name, amount);
				return "success";
			}
		}
		return "people is exist";
	}

	/**
	 * 当企业用户存在时，添加 企业用户关系
	 * 
	 * @author Lyon 创建时间：2016年11月5日 上午9:40:21
	 * @param datacenterFormMap
	 * @return "failed" "success" "people is exist"
	 * @throws Exception
	 */
	public String registeFreezeEnUserExist(DatacenterFormMap datacenterFormMap) throws Exception {
		if (datacenterFormMap.containsKey("cellphone")) {
			String db_name = datacenterFormMap.getStr("db_name");
			List<DatacenterFormMap> list = datacenterFormMap.findByAttribute("cellphone",
					datacenterFormMap.get("cellphone"));
			datacenterFormMap = list.get(0);
			// 找到父级数据库
			DatasourceFormMap datasourceFormMap = FormmapFactory.getBeanFormMap(DatasourceFormMap.class);
			datasourceFormMap.put("db_name", db_name);
			datasourceFormMap = datasourceFormMap.findbyFrist();

			if (datasourceFormMap == null) {
				return "enterprise is not exsit";
			}
			// 保存关系
			ClientDatasourceFormMap clientDatasourceFormMap = new ClientDatasourceFormMap();
			clientDatasourceFormMap.put("client_id", datacenterFormMap.get("id"));
			clientDatasourceFormMap.put("datasource_id", datasourceFormMap.get("id"));
			clientDatasourceFormMap.put("status", 2);
			if (clientDatasourceFormMap.findbyFrist() == null) {
				clientDatasourceFormMap.save();
				return "success";
			}
		}
		return "fields are not matched";
	}

	/**
	 * 注册企业，调用后端DataclientController的addEntity方法;
	 * 
	 * @author 李品良 创建时间：2016年8月25日 下午2:13:29
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("registeEnterprise")
	public synchronized String registeEnterprise(Model model, HttpServletRequest request) {
		try {
			DataclientController dataclientController = new DataclientController();
			return dataclientController.addEntity(model, request);
		} catch (Exception e) {
			e.printStackTrace();
			return "failed";
		}
	}


	/**
	 * 得到 更新人数
	 * 
	 * @author 李品良 创建时间：2016年9月10日 上午11:42:37
	 * @param db_name
	 * @return
	 * @throws Exception
	 */
	// @ResponseBody
	// @RequestMapping("refreshEnSize")
	public String refreshEnSize() throws Exception {
		DatacenterController datacenterController = new DatacenterController();
		HashMap<String, Object> hashMap = getMapFromRequest();
		return datacenterController.refreshEnSize(hashMap.get("db_name").toString());
	}

	/**
	 * 更新企业的信息 1.判断db_name
	 * 
	 * @author Lyon 创建时间：2016年11月5日 上午10:15:40
	 * @return success failed
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("updateEnterpriseInfo")
	public String updateEnterpriseInfo() throws Exception {
		DatasourceFormMap datasourceFormMap = getMapformDataMap(DatasourceFormMap.class, getMapFromRequest());
		String db_name = datasourceFormMap.getStr("db_name");
		if (Common.isNotEmpty(db_name)) {
			List<DatasourceFormMap> list = datasourceFormMap.findByAttribute("db_name", db_name);
			DatasourceFormMap datasourceFormMap2;
			if (list.get(0) == null) {
				return "enterprise isn't exist";
			} else {
				datasourceFormMap2 = list.get(0);
			}
			String id = datasourceFormMap2.getStr("id");
			datasourceFormMap.put("id", id);
			datasourceFormMap.update();
			return "success";
		}
		return "failed";
	}

	/**
	 * 得到企业的信息 1.判断是否存在该企业 参数db_name
	 * 
	 * @author Lyon 创建时间：2016年11月5日 上午10:15:40
	 * @return DatasourceFormMap null
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("runShell")
	@SystemLog(methods = "runShell", module = "InterfaceController")
	public void runShell() throws Exception {
		InvokeBatUtil invokeBatUtil = InvokeBatUtil.getInvokeBatUtil();
		invokeBatUtil.runBatFromStr("sh /dtd/backup/log_basic.sh");
	}

	/**
	 * 得到企业的信息 1.判断是否存在该企业 参数db_name
	 * 
	 * @author Lyon 创建时间：2016年11月5日 上午10:15:40
	 * @return DatasourceFormMap null
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("getEnterpriseInfo")
	public DatasourceFormMap getEnterpriseInfo() throws Exception {
		DatasourceFormMap datasourceFormMap = getMapformDataMap(DatasourceFormMap.class, getMapFromRequest());
		String db_name = datasourceFormMap.getStr("db_name");
		int GET_MODE=getPara("GET_MODE")==null?0:datasourceFormMap.getInt("GET_MODE");
			
		if (Common.isNotEmpty(db_name)) {
			DatasourceFormMap datasourceFormMap2 = datasourceFormMap.findbyFrist();
			if (datasourceFormMap2!=null&&!datasourceFormMap2.containsKey("en_filepath")&& GET_MODE==1) {
				String id=datasourceFormMap2.getStr("id");
				String result=Axis2Client.RPCClient(id);
				datasourceFormMap2.put("en_filepath", result);
				datasourceFormMap2.update();
			}
			return datasourceFormMap2;
		}
		return null;
	}

	
	
	/**
	 * 企业员工保存附件信息
	 * @author Lyon 创建时间：2016年11月28日 下午3:10:40
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("saveAccessory")
	public String saveAccessory() throws Exception {
		AccessoryFormMap accessoryFormMap = getMapformDataMap(AccessoryFormMap.class, getMapFromRequest());
		String db_name = accessoryFormMap.getStr("db_name");
		if (Common.isNotEmpty(db_name)) {
			accessoryFormMap.save();
			return "success";
		}
		return "failed";
	}
	
	/**
	 * 浏览相对应的企业员工保存附件信息
	 * @author Lyon 创建时间：2016年11月28日 下午3:10:40
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("getAccessory")
	public List<AccessoryFormMap> getAccessory() throws Exception {
		AccessoryFormMap accessoryFormMap = getMapformDataMap(AccessoryFormMap.class, getMapFromRequest());
		String dbName=accessoryFormMap.get("dbName")==null?null:accessoryFormMap.getStr("dbName");
		String worker=accessoryFormMap.get("worker")==null?null:accessoryFormMap.getStr("worker");
		List<AccessoryFormMap> list=null;
		if (Common.isNotEmpty(worker)&&Common.isNotEmpty(dbName)) {
			list=accessoryFormMap.findByNames_Page();
		}
		return list;
	}
	
	/**
	 * 企业员工保存附件信息
	 * @author Lyon 创建时间：2016年11月28日 下午3:10:40
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("updateEnFilepath")
	public String updateEnFilepath() throws Exception {
		DatasourceFormMap datasourceFormMap = getMapformDataMap(DatasourceFormMap.class, getMapFromRequest());
		String db_name = datasourceFormMap.getStr("db_name");
		if (Common.isNotEmpty(db_name)) {
			datasourceFormMap.updateForKey();
			return "success";
		}
		return "failed";
	}
}
